package com.fch.sdlibrary;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.fch.sdlibrary.entity.BaseResponse;
import com.fch.sdlibrary.entity.Book;
import com.fch.sdlibrary.global.MyGlobal;
import com.fch.sdlibrary.util.TokenInterceptor;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;

public class BookActivity extends AppCompatActivity {

    private ImageView imageView;
    private TextView bookName, bookAuthor, bookClazz, bookQuantity, bookIsbn, bookText;
    private Button button;
    private String bookId;

    private Book book;

    private BaseResponse baseResponse;
    private Gson gson = new Gson();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book);

        init();
        send();

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(BookActivity.this);
                builder.setMessage("是否确认借阅《" + book.getBookName() + "》?");
                builder.setPositiveButton("确认借阅", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int arg1) {
                        // TODO Auto-generated method stub
                        doBorrow();
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.dismiss();
                    }

                });
                builder.create().show();
            }
        });
    }

    /**
     * 执行借书操作
     */
    private void doBorrow() {
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new TokenInterceptor(this))//拦截器
                .build();//创建Http客户端

        Request request = new Request.Builder()
                .url(MyGlobal.PATH + "Borrow?bookId=" + book.getBookId())//***.***.**.***为本机IP，xxxx为端口，/  /  为访问的接口后缀
                .post(new RequestBody() {
                    @Override
                    public MediaType contentType() {
                        return MyGlobal.JSON;
                    }

                    @Override
                    public void writeTo(BufferedSink sink) throws IOException {

                    }
                })
                .build();//创建Http请求
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败的处理
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功返回结果
                //如果希望返回的是字符串
                final String responseData = response.body().string();
                baseResponse = new BaseResponse<Book>();
                Type type = new TypeToken<BaseResponse<Book>>() {
                }.getType();
                baseResponse = gson.fromJson(responseData, type);
                book = (Book) baseResponse.getData();

                if (baseResponse.getCode() == 401) {
                    Intent intent = new Intent(BookActivity.this, LoginActivity.class);
                    startActivity(intent);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(BookActivity.this, "请登录", Toast.LENGTH_SHORT).show();
                        }
                    });
                    finish();
                    return;
                }if (baseResponse.getCode() == 200) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(BookActivity.this, baseResponse.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    });
                    finish();
                }
            }
        });
    }

    /**
     * 发送http请求
     */
    private void send() {
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new TokenInterceptor(this))//拦截器
                .build();//创建Http客户端
        Request request = new Request.Builder()
                .url(MyGlobal.PATH + "QueryBook?id=" + bookId)//***.***.**.***为本机IP，xxxx为端口，/  /  为访问的接口后缀
                .get()
                .build();//创建Http请求
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败的处理
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功返回结果
                //如果希望返回的是字符串
                final String responseData = response.body().string();
                baseResponse = new BaseResponse<Book>();
                Type type = new TypeToken<BaseResponse<Book>>() {
                }.getType();
                baseResponse = gson.fromJson(responseData, type);
                book = (Book) baseResponse.getData();

                if (baseResponse.getCode() == 401) {
                    Intent intent = new Intent(BookActivity.this, LoginActivity.class);
                    startActivity(intent);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(BookActivity.this, "请登录", Toast.LENGTH_SHORT).show();
                        }
                    });
                    finish();
                    return;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 更新UI的操作
                        Glide.with(imageView.getContext()).load(MyGlobal.IMG_PATH + book.getBookImg()).into(imageView);
                        bookName.setText(book.getBookName());
                        bookAuthor.setText(book.getBookAuthor());
                        bookClazz.setText("分类：" + book.getBookClassName());
                        bookQuantity.setText("库存：" + book.getBookQuantity().toString());
                        bookIsbn.setText("ISBN：" + book.getBookIsbn());
                        bookText.setText("简介：" + book.getBookText());
                        if (book.getBookQuantity() < 1) {
                            button.setBackgroundResource(R.drawable.but_err);
                            button.setEnabled(false);
                        }
                    }
                });
            }
        });
    }

    private void init() {
        imageView = findViewById(R.id.book_img);
        bookName = findViewById(R.id.book_name);
        bookAuthor = findViewById(R.id.book_author);
        bookClazz = findViewById(R.id.book_class);
        bookQuantity = findViewById(R.id.book_quantity);
        bookIsbn = findViewById(R.id.book_isbn);
        bookText = findViewById(R.id.book_text);
        button = findViewById(R.id.book_button);

        Intent intent = getIntent();
        bookId = intent.getStringExtra("id");
    }
}
